package internal

import (
	"context"
	"fmt"
	"github.com/name5566/leaf/gate"
	"reflect"
	ConstValue "server/const"
	"server/g"
	"server/libs/db"
	"server/libs/jwttoken"
	"server/libs/pwdencode"
	snowflake2 "server/libs/snowflake"
	"server/model"
	"server/msg"
	"server/msg/pb"
	"strconv"
	"strings"
)

const (
	CHINESE_LANG = "zh"
	ENGLISH_LANG = "en"
	SPANISH_LANG = "es"
	FRANCH_LANG  = "fr"
)
const (
	PREFIX_USER = "USER"
)

func init() {

	//所有Request
	for k, v := range msg.MsgInfo {
		_ = k
		msgstr := reflect.TypeOf(v).String()
		msgName := strings.Split(msgstr, ".")
		if msgName[1] == "GameMessageRequest" {
			handler(v, GameMessageRequest)
			continue
		}
		if msgName[1] == "GameLoginRequest" {
			handler(v, GameLoginRequest)
			continue
		}
		if msgName[1] == "GameHeartbeatRequest" {
			handler(v, GameHeartbeatRequest)
			continue
		}
		if msgName[1] == "GameUserRequest" {
			handler(v, GameUserRequest)
			continue
		}

		if msgName[1] == "GameRegisterRequest" {
			handler(v, GameRegisterRequest)
			continue
		}

		if msgName[1] == "GameLoginPWDRequest" {
			handler(v, GameLoginPWDRequest)
			continue
		}

		if msgName[1] == "GameSquarePosRequest" {
			handler(v, UpdateMetaSquare)
			continue
		}
		if msgName[1] == "GameNearRequest" {
			handler(v, GetNearUserSquare)
			continue
		}

		msgType := reflect.TypeOf(v)
		if msgType.String()[len(msgType.String())-7:] == "Request" {
			handler(v, Request)
		}
	}
}

func handler(m interface{}, h interface{}) {
	skeleton.RegisterChanRPC(reflect.TypeOf(m), h)
}

type Hello struct {
	Name string
}

func JWT_TOKEN_CHECK(id string, jwtToken string) bool {
	ctx := context.Background()
	data := db.Redis().Get(ctx, PREFIX_USER+"-"+id)
	if data.Val() != jwtToken {
		return false
	}
	return true
}

// 登录
func GameLoginRequest(args []interface{}) {

	// 收到的 Hello 消息
	agent := args[1].(gate.Agent)
	message := args[0].(*pb.GameLoginRequest)
	if message.Token == "" {
		return
	}
	data, err := jwttoken.ParseToken(message.Token)
	if err != nil && data == nil {
		agent.WriteMsg(&pb.GameLoginResponse{
			Code: 1,
		})
		return
	}
	//UserLang := message.GetLang()
	userData := g.UserData{}
	//userData.Id = data["id"].(string)
	ReadId := data["id"].(string)
	if !JWT_TOKEN_CHECK(ReadId, message.Token) {
		agent.WriteMsg(&pb.GameLoginResponse{
			Code: 1100,
		})
		return
	}
	userData.Id, err = strconv.ParseInt(ReadId, 10, 64)
	if err != nil {
		return
	}
	//userData.Lang = lang.GetValidLang(UserLang)
	userinfo, ok := g.Userinfo.Load(userData.Id)
	if ok {
		userData = userinfo.(g.UserData)
	}
	userData.Agent = agent
	//userData.GameCode = "game"
	g.Userinfo.Store(userData.Id, userData)
	agent.SetUserData(userData)
	agent.WriteMsg(&pb.GameLoginResponse{
		GameCode:    "userData.GameCode",
		GameCodeBet: "userData.GameCodeBet",
		// State:       userData.GameCodeBet,
	})
}

// 注册
func GameRegisterRequest(args []interface{}) {

	// 收到的 Hello 消息
	agent := args[1].(gate.Agent)
	message := args[0].(*pb.GameRegisterRequest)
	fmt.Println(message.UserName)
	fmt.Println(message.Password)
	var Count int64
	err := db.Mysql().Model(&model.HomeUserInfo{}).Where("username = ?", message.UserName).Count(&Count).Error
	if err != nil {
		agent.WriteMsg(&pb.GameErrMsgResponse{
			ErrorCode: 1000,
			ErrorMsg:  err.Error(),
		})
		return
	}
	if Count != ConstValue.Zero_Value {
		agent.WriteMsg(&pb.GameErrMsgResponse{
			ErrorCode: 1001,
			ErrorMsg:  message.UserName + " already registered!",
		})
		return
	}
	id := snowflake2.GetIdInt64()
	err = db.Mysql().Model(&model.HomeUserInfo{}).Create(&model.HomeUserInfo{
		ID:       id,
		Nickname: message.NickName,
		Mobile:   message.Mobile,
		Username: message.UserName,
		Email:    message.Email,
		Avatar:   message.Avatar,
		Password: pwdencode.PasswordHex(message.Password),
		SexDict:  message.SexDict,
	}).Error
	if err != nil {
		agent.WriteMsg(&pb.GameErrMsgResponse{
			ErrorCode: 1000,
			ErrorMsg:  err.Error(),
		})
		return
	}
	agent.WriteMsg(&pb.GameRegisterResponse{
		RegisResult: "Register Success",
		Code:        0,
		UserId:      id,
	})
}

// 登录
func GameLoginPWDRequest(args []interface{}) {
	var (
		err       error
		userModel model.HomeUserInfo
	)
	agent := args[1].(gate.Agent)
	message := args[0].(*pb.GameLoginPWDRequest)
	fmt.Println(message.UserName)
	fmt.Println(message.Password)
	err = db.Mysql().Model(&model.HomeUserInfo{}).
		Where("username  = ?", message.UserName).
		Where("password  = ?", pwdencode.PasswordHex(message.Password)).
		First(&userModel).Error
	if err != nil {
		if err.Error() == "record not found" {

			agent.WriteMsg(&pb.GameErrMsgResponse{
				ErrorCode: 1002,
				ErrorMsg:  "username or password error!",
			})
			return
		} else {
			agent.WriteMsg(&pb.GameErrMsgResponse{
				ErrorCode: 1003,
				ErrorMsg:  err.Error(),
			})
			return
		}
	}
	userData := g.UserData{}
	userData.Id = userModel.ID
	userData.Agent = agent
	g.Userinfo.Store(userData.Id, userData)
	agent.SetUserData(userData)
	agent.WriteMsg(&pb.GameLoginPWDResponse{
		LoginResult: "Success",
		LoginCode:   0,
		UserId:      userModel.ID,
		SexDict:     userModel.SexDict,
	})
	return
}

// 获取消息
func GameMessageRequest(args []interface{}) {
	// agent := args[1].(gate.Agent)
	// if agent.UserData() == nil {
	// 	return
	// }
	// messageId := make(map[int64]string)
	// msg.Processor
	// msg.Processor.Range(func(id uint16, t reflect.Type) {
	// 	messageId[int64(id)] = strings.Split(t.String(), ".")[1]
	// })
	// agent.WriteMsg(&pb.GameMessageResponse{
	// 	Message: messageId,
	// })
}

// 心跳
func GameHeartbeatRequest(args []interface{}) {
	agent := args[1].(gate.Agent)
	if agent.UserData() == nil {
		return
	}
	agent.WriteMsg(&pb.GameHeartbeatResponse{})
}

// 获取用户信息
func GameUserRequest(args []interface{}) {
	agent := args[1].(gate.Agent)
	if agent.UserData() == nil {
		return
	}
	userData := agent.UserData().(g.UserData)
	agent.WriteMsg(&pb.GameUserResponse{
		Id:       userData.Id,
		Nickname: "玩家-" + strconv.FormatInt(userData.Id, 10),
		Avatar:   "",
	})
}

// 发送接受请求消息
func Request(args []interface{}) {
	// fmt.Println(msgName)
	// fmt.Println(gameName)
	agent := args[1].(gate.Agent)
	if agent.UserData() == nil {
		return
	}
	u := agent.UserData().(g.UserData)
	msgstr := reflect.TypeOf(args[0]).String()
	msgName := strings.Split(msgstr, ".")
	if strings.HasPrefix(msgName[1], "G1") {
		g.G1.Go("Push", u.Id, args[0])
		return
	}
}
